package cz.jprmr.lorn.client.utils;

import java.util.HashMap;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;

import cz.jprmr.lorn.client.pages.homepage.HomePage;
import cz.jprmr.lorn.client.pages.loginpage.LoginPage;

public class PageController implements ValueChangeHandler<String> {
	
	private static PageController instance = null;
	   
	private PageController() {
	    String initToken = History.getToken();
	    if (initToken.length() == 0) {
	      History.newItem("page=home");
	    }
	    
		// Add history listener
	    History.addValueChangeHandler(this);

	    // Now that we've setup our listener, fire the initial history state.
	    History.fireCurrentHistoryState();
	}
   
	public static PageController getInstance() {
		if(instance == null) {
			instance = new PageController();
		}
		return instance;
	}

	public void onValueChange(ValueChangeEvent<String> event) {
		System.out.println(event.getValue());
		HashMap<String, String> tokens = parseHistoryToken(event.getValue());
		
		String page = tokens.get("page");
		System.out.println(page);
		
		RootPanel root = RootPanel.get("rootSpace");
		
		if (page.equals("home")) {	
			root.add(new HomePage());
		} else if (page.equals("login")) {			
			root.add(new LoginPage());
		}
	}
	
	private HashMap<String, String> parseHistoryToken(String token) {
		HashMap<String, String> tokens = new HashMap<String, String>();
		String[] pairs = token.split("&");
		for(String pair : pairs) {
			String[] keyValue = pair.split("=");
			tokens.put(keyValue[0], keyValue[1]);
		}
		return tokens;
	}
}